var counter;
var total;
var originalTotal;
$(document).ajaxStop(function() {
    if (counter == 0) {
        makePayment();
        counter = null;
    }
});

function checkNumeric(element) {
    var regex = /^[0-9]+$/;
    if (element.value.match(regex)) {
        $('#number').removeClass('error');
        $('#numberErr').hide();
        return true;
    } else {
        element.value = '';
        $('#number').addClass('error');
        $('#numberErr').show().text('Enter numeric only');
        return false;
    }
}

function generateTemplete() {
    if ($('#number').val() !== '') {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: $('#ticketno').serialize(),
            success: function(result) {
                if (!result.error) {
                    $('#ticketdiv').html(result.forms);
                    $(document).foundation('forms');
                    $('#numberErr').hide();
                    $('#number').removeClass('error');
                } else {
                    $('#ticketdiv').html('');
                    $('#number').addClass('error');
                    $('#numberErr').show().text(result.forms);
                }
                $('#overlay').fadeOut('fast');
            }
        });

    } else {
        $('#number').addClass('error');
        $('#numberErr').show().text('Required');
    }
}

function showModal(element) {
    $('#coachmap').html('');
    $('#myModal').foundation('reveal', 'open');
    var id = element.id;
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    $.ajax({
        type: 'POST',
        url: 'action.php',
        data: {action: 'getCoach'},
        success: function(result) {
            $('#coach').empty().append(new Option('Select Coach', 0));
            for (var i = 0; i < result.length; i++) {
                $('#coach').append(new Option(result[i], result[i]));
            }
            $(document).foundation('forms');
            $('#ticketnumber').val(id);
            $('#overlay').fadeOut('fast');
        }
    });
}

function getCoachmap() {
    if ($('#coach').val() != 0) {
        var docHeight = $(document).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.ajax({
            type: 'POST',
            url: 'action.php',
            data: $('#seatform').serialize(),
            success: function(result) {
                $('#coachmap').html(result);
                $('#overlay').fadeOut('fast');
            }
        });
    }
}

function getSeatid(element, seatno, coach) {
    var id = $(element).attr('id');
    var ticketnumber = $('#ticketnumber').val();
    var seatid = 'seatid' + ticketnumber.substring(6);
    var docHeight = $(window).height();
    $('#overlay').fadeIn('fast').height(docHeight);
    var currentSeat = $('#' + seatid).val();
    if (currentSeat != '') {
        if (id != currentSeat) {
            $.post('action.php', {
                action: 'unlockSeat',
                id: currentSeat}
            );
        }
    }
    $('#' + seatid).val(id);
    $.post('action.php', {
        action: 'lockSeat',
        id: id
    }, function(data) {
        if (!data.error) {
            $('#' + ticketnumber).val(coach + ' - ' + seatno);
            $('#myModal').foundation('reveal', 'close');
        } else {
            alert(data.message);
        }
        $('#overlay').fadeOut('fast');
    });
}

function createTicket() {
    var basicfare = $('#fare').val();
    var totalticket = $('#number').val();
    var discount = $('#discount').val();
    var selectedseat = totalticket;
    total = 0;
    for (var i = 0; i < totalticket; i++) {
        var fare = basicfare * $('#type' + (i+1)).val();
        console.log("Basic fare is " + fare);
        console.log("Currently discount is "+discount);
        fare *= discount;
        total += fare;
        console.log("Currently total is "+total);
        if ($('#seatno' + (i + 1)).val() != '') {
            selectedseat--;
        }
    }
    originalTotal = total;
    total -= $('#value').val();
    if (selectedseat == 0) {
        if (confirm('Total amount of tickets is RM' + ((total < 0) ? '0' : total.toFixed(2)) + '. Proceed to payment?\nNote that payment will be done automatically when you click ok.')) {
            counter = 0;
            var docHeight = $(window).height();
            $('#overlay').fadeIn('fast').height(docHeight);
            var forms = document.getElementsByClassName('postable custom');
            for (var i = 0, f = forms.length; f > i; i++) {
                counter++;
                console.log('Counter++ now, value = ' + counter);
                $.ajax({
                    type: 'POST',
                    url: 'action.php',
                    data: $(forms[i]).serialize(),
                    success: function(result) {
                        if (!result.error) {
                            counter--;
                            console.log('No error, counter-- now, value = ' + counter);
                        } else {
                            message = 'Something went wrong, please try again later.';
                        }
                    }
                });
            }
        } else {
            total = 0;
        }
    } else {
        alert('please select all seat 1st');
    }
}

function makePayment() {
    console.log('Making payment');
    $.post('action.php', {
        action: 'makePayment'
    }, function(data) {
        if (!data.error) {
            console.log('Payment done');
            console.log('Adding to sales log, total amount is ' + originalTotal);
            updateSalesLog();
            console.log('Added to sales log');
            console.log('Cleaning up');
            cleanUp();
            console.log('Cleanup done');
        } else {
            alert(data.message);
        }
    });
}

function updateSalesLog() {
    $.post('action.php', {
        action: 'addSalesLog', total: originalTotal, type: 'online'
    });
}

function cleanUp() {
    $.post('action.php', {
        action: 'cleanUp'
    }, function() {
        $('#overlay').fadeOut('fast');
        window.location.replace('success.php');
    });
}

function atomicCleanUp(url) {
    $.post('action.php', {
        action: 'backCleanUp'
    }, function() {
        window.location.replace(url);
    });
}

function enableCoupon(element) {
    if ($(element).is(':checked')) {
        $('#coupon').prop('disabled', false);
        $('#submitcoupon').prop('disabled', false);
    } else {
        $('#coupon').prop('disabled', true);
        $('#submitcoupon').prop('disabled', true);
    }
}

function checkCoupon() {
    if ($('#coupon').val() != '') {
        var docHeight = $(window).height();
        $('#overlay').fadeIn('fast').height(docHeight);
        $.post('action.php',
                $('#couponform').serialize(),
                function(data) {
                    if (!data.error) {
                        $('#coupon').removeClass('error');
                        $('#couponErr').addClass('hidden-field');
                        $('#coupon').prop('disabled', true);
                        $('#submitcoupon').prop('disabled', true);
                        $('#check').prop('disabled', true);
                        $('#couponresult').fadeIn('slow').addClass('success').html(data.message).delay(4000).fadeOut('slow');
                        $('#value').val(data.value);
                        $('#overlay').fadeOut('fast');
                    } else {
                        $('#coupon').addClass('error');
                        $('#couponErr').fadeIn('fast').html(data.message).delay(4000).fadeOut('fast');
                        $('#couponresult').html('').hide();
                        $('#overlay').fadeOut('fast');
                    }
                });
    } else {
        $('#coupon').addClass('error');
        $('#couponErr').fadeIn('fast').html('Required').delay(4000).fadeOut('fast');
    }
}

